package com.xms.security.verification.service;

import com.xms.security.verification.core.IVerifyProvider;
import com.xms.security.verification.model.VerifyValue;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * 图片文字验证码提供者
 * </p>
 *
 * @author migo
 * @since 2021/11/6
 */
@Service
public class ImageTextVerifyProvider implements IVerifyProvider {
    private final static String CACHE_KEY = "verifycode";

    @Override
    public VerifyValue get() {
        VerifyValue result = RandomImageGenernator.generate(80, 28);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        //放到缓存
        request.getSession(true).setAttribute(CACHE_KEY, result.code);
        return result;
    }

    @Override
    public boolean valid(String code) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        HttpSession session = request.getSession(true);
        //从缓存获取
        Object value = session.getAttribute(CACHE_KEY);
        //从缓存清除
        session.removeAttribute(CACHE_KEY);
        return value != null && value.toString().equalsIgnoreCase(code);
    }
}
